<template>

  <el-dialog
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    :append-to-body="true"
    title="试题预览"
    width="90vw"
    @close="handleClose">


    <div v-if="dialogVisible" class="multi-box">
      <div class="multi-t">批量设置</div>
      <div class="multi-t2">所属题库：</div>
      <repo-select v-model="postForm.repoId" @code="repoChange" />
      <div v-if="postForm.repoId" class="multi-t2">所属章节：</div>
      <chapter-select v-model="postForm.chapterId" :repo-id="postForm.repoId" />
      <div class="multi-t2">难度级别：</div>
      <dic-list-select v-model="postForm.quLevel" dic-code="qu_level"/>
      <div class="multi-t2">知识点：</div>
      <key-point-select v-model="postForm.pointList" :root="pointRoot"/>
    </div>

    <div v-if="!firstReady" class="mnt-tips">试题解析中，请稍候...</div>

    <div v-loading="!firstReady" v-if="dialogVisible" id="dialog-body" style="min-height: 90vh">

      <!-- 第一题预加载 -->
      <div v-if="quList && quList.length > 0" id="qu-0" style="padding-top: 30px">
        <qu-item-save
          :value="quList[0]"
          :child="false"
          :update="true"
          @loaded="firstLoaded()"/>
        <div style="padding:10px 0; text-align: right; cursor: pointer;">
          <el-button type="danger" icon="el-icon-remove" @click="removeQu(0)">移除</el-button>
        </div>
      </div>

      <div v-if="firstReady">
        <template v-for="(item, index) in quList">
          <div v-if="index > 0" :key="index" :id="`qu-${index}`" style="padding-top: 30px">
            <qu-item-save
              :value="item"
              :child="false"
              :update="true"/>
            <div style="padding:10px 0; text-align: right; cursor: pointer;">
              <el-button type="danger" icon="el-icon-remove" @click="removeQu(index)">移除</el-button>
            </div>
          </div>
        </template>
      </div>
    </div>

    <div slot="footer" class="dialog-footer flex-bt">

      <div class="calc-box">
        <div>
          总题数：<span style="color: #0a84ff; font-size: 18px">{{ totalQu }}</span>
        </div>
        <div style="font-size: 20px">/</div>
        <div>
          已保存：<span style="color: #ff3403; font-size: 18px">{{ savedQu }}</span>
        </div>
      </div>

      <div>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="confirmSave">确认入库</el-button>
      </div>


    </div>


  </el-dialog>

</template>

<script>

import QuItemShow from '@/views/admin/repo/qu/components/QuItemShow.vue'
import ChapterSelect from '@/components/ChapterSelect/index.vue'
import KeyPointSelect from '@/components/KeyPointSelect/index.vue'
import KeyPointTreeSelect from '@/components/KeyPointTreeSelect/index.vue'
import QuItemSave from '@/views/admin/repo/qu/components/QuItemSave.vue'
import DicListSelect from '@/components/DicListSelect/index.vue'
import { textToJson } from '@/utils/qu-parser'
import { saveData } from '@/api/qu/qu'
import { scrollToDom } from '@/utils/scroll-to'

export default {
  name: 'AiPreviewDialog',
  components: { DicListSelect, QuItemSave, KeyPointTreeSelect, KeyPointSelect, ChapterSelect, QuItemShow },
  props: {
    quStr: String,
    visible: {
      type: Boolean,
      default: false
    },
    repoId: String
  },
  data() {
    return {
      firstReady: false,
      quList: [],
      dialogVisible: false,
      pointRoot: '-1',
      loading: false,
      postForm: {
        repoId: '',
        pointList: [],
        quLevel: '',
        chapterId: ''
      },
      // 保存进度
      totalQu: 0,
      savedQu: 0
    }
  },


  watch: {
    visible: {
      handler() {
        this.dialogVisible = this.visible
        if (this.visible) {
          // 打开窗口时进行解析
          this.buildQuList()
        } else {
          this.firstReady = false
        }
      }
    },
    repoId: {
      handler() {
        this.postForm.repoId = this.repoId
      }
    },
    postForm: {
      handler(val) {
        this.batchFill(val.repoId, val.quLevel, val.chapterId, val.pointList)
      },
      deep: true
    }
  },

  created() {
    this.dialogVisible = this.visible
    // 字符转换为JSON
    this.buildQuList()
  },

  methods: {

    // 转换题目
    async buildQuList() {
      this.quList = []

      if (this.quStr) {
        try {
          this.quList = textToJson(this.quStr)

          this.totalQu = this.quList.length
        } catch (error) {
          console.error(error)
          this.$message.error('没有正确生成题目，请检查数据格式！')
          this.handleClose()
        }
        if (this.quList.length === 0) {
          this.$message.error('没有正确生成题目，请检查数据格式！')
          this.handleClose()
        }

        // 构建默认参数
        for (let i = 0; i < this.quList.length; i++) {
          const item = this.quList[i]
          if (item.quType === 'saq') {
            this.$set(item, 'manual', true)
          }

          // 填充题库
          this.$set(item, 'repoId', this.postForm.repoId || this.repoId || '')
        }


        // 题库填充
        if (this.repoId && !this.postForm.repoId) {
          this.postForm.repoId = this.repoId
        }
      }
    },

    // 批量填充
    batchFill(repoId, quLevel, chapterId, pointList) {
      for (let i = 0; i < this.quList.length; i++) {
        if (repoId) {
          this.quList[i].repoId = repoId
        }
        if (chapterId) {
          this.quList[i].chapterId = chapterId
        }
        if (quLevel) {
          this.quList[i].quLevel = quLevel
        }
        if (pointList && pointList.length > 0) {
          this.quList[i].pointList = pointList
        }
      }

      this.$forceUpdate()
    },

    // 知识点
    repoChange(v) {
      this.pointRoot = v.pointCode
      this.postForm.pointCodes = []
    },

    handleClose() {
      this.$emit('update:visible', false)
      this.$emit('close')
    },

    async confirmSave() {
      this.savedQu = 0
      this.loading = true

      const repoId = this.postForm.repoId

      if (!repoId) {
        this.$message.error('请选择一个题库！')
        this.loading = false
        return
      }

      const check = await this.checkData()
      if (!check) {
        this.loading = false
        return
      }

      for (let i = this.quList.length - 1; i >= 0; i--) {
        const item = this.quList[i]

        // 未保存的
        await saveData(item).then(() => {
          // 标记为已入库
          this.savedQu++
          // 移除已保存的
          this.removeQu(i)
        }).catch(() => {
          this.loading = false
        })

        if (i === 0) {
          this.loading = false

          // 全部入库成功
          if (this.savedQu === this.totalQu) {
            setTimeout(() => {
              this.handleClose()

              // 后续操作
              this.$confirm('试题已全部入库', '提示', {
                confirmButtonText: '返回出题页面',
                cancelButtonText: '进入题库查看',
                type: 'warning'
              }).then(() => {
                window.location.reload()
              }).catch(() => {
                this.$router.push({ name: 'QuList', query: { repoId: repoId }})
              })
            }, 1000)
          }
        }
      }
    },
    removeQu(i) {
      this.quList.splice(i, 1)
    },

    // 校验数据
    async checkData() {
      for (let i = 0; i < this.quList.length; i++) {
        const item = this.quList[i]
        if (!item.quLevel) {
          this.$message.error('第' + (i + 1) + '题难度等级为空！')
          this.goAnchor(i)
          return false
        }
      }

      return true
    },
    // 到指定位置
    goAnchor(index) {
      const dom = document.querySelector('.el-dialog__body')
      const anchor = document.getElementById(`qu-${index}`)
      console.log(anchor)
      const to = anchor.offsetTop - 20
      // 滑动到指定位置
      scrollToDom(dom, to, 600, function() {
      })
    },
    firstLoaded() {
      this.firstReady = true
    }
  }
}
</script>

<style scoped>


.multi-box{
  padding:10px;
  display: flex;
  align-items: center;
  background: #304156;
  margin-bottom:20px;
  position: fixed;
  top: 20px;
  width: calc(100% - 40px);
  z-index: 2
}

.multi-t{
  color: #1890FF;
  font-weight: 700;
  padding-right: 50px
}
.multi-t2{
  color: #fff;
  padding-left: 10px
}

.mnt-tips{
  text-align: center;
  font-size: 20px;
  font-weight: 700;
  padding: 100px 0 50px 0
}

.calc-box{
  font-weight: 700;
  font-size: 14px;
  width: 180px;
  display: flex;
  justify-content: space-between;
}
</style>
